<template>
	<div id="SearchPage">
		<div v-if="ReceiveData.SelectData === '1'" id="ShopBox">
			<div class="list_box">
				<div v-for="(shops,index) in GoodsData" :key="index" class="list_item">
					<div class="goods-list-itme" :style="{
              backgroundImage: 'url(' + shops.mid_images + ')',
              backgroundPosition: 'center center',
              backgroundRepeat: 'no-repeat',
              backgroundPositionX: '100%',
              backgroundPositionY: '100%',
            }">
						<div class="logo">
							<img :src="shops.detail.cLogoUrl" :alt="shops.detail.cShopName" class="logo-img">
						</div>
						<div class="shop-name">
							{{ shops.detail.cShopName }}
						</div>
						<div class="shop-type">
							{{ shops.detail.iType === 1 ? "自营" : "非自营" }}
						</div>
						<div class="shop-button" @click="GtShop(shops.detail)">
							进店
						</div>
					</div>
				</div>
			</div>
		</div>
		<div v-if="ReceiveData.SelectData === '2'" id="GoodsBox">
			<GoodsTop ref="SellCakesTopRefs" :shopid="ReceiveData.ShopID" @GoodsTopList="GoodsTopList" />
			<div class="goods_body">
				<div v-for="(item, index) in GoodsListData" :key="index" class="goods-item" @click="todetail(item)">
					<div class="goods-img">
						<img :src="item.defaultAlbum" alt="">
					</div>
					<div class="goods-info">
						<div class="goods-info-left">
							<div class="name">
								{{ item.cProductShowName }}
							</div>
							<div class="price_box">
								<div class="price">
									￥{{ item.fSalePrice }}
								</div>
								<div class="text">
									已有{{ item.iSales }}人付款
								</div>
							</div>
						</div>
						<div class="goods-info-right">
							<img class="item_img" :src="item.FocusStatus? guanzhu : notguanzhu"
								@click.stop="focus(item)">
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
	// import ShopIndexNav from "@/components/shopindex/ShopIndexNav"; // banner下自营log
	// import ShopIndexBanner from "@/components/shopindex/ShopIndexBanner"; // 店铺首页BANNER
	import GoodsTop from "@/components/shopindex/GoodsTop.vue"; // 商品顶部
	import guanzhu from '../../assets/img/zan_selected.png'; // 已关注
	import notguanzhu from '../../assets/img/zan.png'; // 未关注
	export default {
		name: 'SearchPage',
		components: {
			GoodsTop, // 商品顶部
			// ShopIndexNav, // banner下自营log
			// ShopIndexBanner, // 店铺首页BANNER
		},
		data() {
			return {
				notguanzhu: notguanzhu, // 未关注
				guanzhu: guanzhu, // 已关注
				GoodsData: [],
				GoodsListData: [], // 商品数据
				ReceiveData: {
					SelectData: '1',
					InputData: '',
					ShopID: '',
				},
			}
		},
		/* HTML DOM加载后马上执行的，如赋值*/
		computed: {},

		/* 观察Vue实例上的数据变动 */
		watch: {
			$route(to, from) {
				console.log('to11', to, from)
				this.ReceiveData.SelectData = to.query.select
				this.ReceiveData.InputData = to.query.input
				this.ReceiveData.ShopID = this.$route.query.ShopID
				if (this.ReceiveData.SelectData === '1') {
					this.getShopsData(this.ReceiveData.InputData)
				} else {
					this.GoodsTopList() // 获取商品列表
				}
			}
		},

		/* 模板渲染成html前调用，即通常初始化某些属性值，然后再渲染成视图 */
		created() {},

		/* 模板渲染成html后调用，通常是初始化页面完成后，再对html的dom节点进行一些需要的操作 */
		mounted() {

			this.ReceiveData.SelectData = this.$route.query.select
			this.ReceiveData.InputData = this.$route.query.input
			this.ReceiveData.ShopID = this.$route.query.ShopID
			if (this.$route.query.select === '1') {
				this.getShopsData(this.ReceiveData.InputData)
			} else {
				this.GoodsTopList() // 获取商品列表
			}

			// 监听浏览器返回
			if (window.history && window.history.pushState) {
				// 向历史记录中插入了当前页
				history.pushState(null, null, document.URL);
				window.addEventListener('popstate', this.goBack, false);
			}
		},
		destroyed() {
			window.removeEventListener('popstate', this.goBack, false);
		},
		/* methods则必须要有一定的触发条件才能执行 */
		methods: {
			goBack() {
				console.log("点击了浏览器的返回按钮");
				window.history.back();
				history.pushState(null, null, document.URL);
			},
			// 获取导航切换值
			ChangeType(ChangeType) {
				console.log("获取导航id", ChangeType);
			},
			// 获取店铺列表
			getShopsData() {
				let params = {
					page: 1,
					limit: 100,
				};
				this.$api.home.ShopsList(params).then((res) => {
					if (res.code == 1) {
						if (this.ReceiveData.InputData === '') {
							this.GoodsData = res.data.data;
						} else {
							let arr = res.data.data
							let detection = this.ReceiveData.InputData
							let NewGoodsData = {}
							let results = []
							console.log('ShopName', this.ReceiveData.InputData)
							if (JSON.stringify(arr).indexOf(detection) !== -1) {
								arr.map(value => {
									if (detection === value.detail.cShopName) {
										NewGoodsData = value
									}
								})
								console.log('NewGoodsData', NewGoodsData)
								if (JSON.stringify(NewGoodsData) === '{}') {
									this.$message.error('未找到相关店铺')
									this.GoodsData = res.data.data
								} else {
									results.push(NewGoodsData)
									this.GoodsData = results
								}
							}
						}
					} else {
						this.$message.error(res.msg);
					}
				})
			},
			// 获取商品列表
			// 商品列表---分类，地区，排序，搜索组件值
			/*
			 * classifyId, 分类
			 * regionId, 地区
			 * areaId, 排序
			 * keywords 搜索
			 * PriceSorting:0 , 价格排序
			 */
			GoodsTopList(classifyId, regionId, areaId, keywords, PriceSorting) {
				let that = this
				this.ScreeningObj = {
					classifyId: classifyId,
					regionId: regionId,
					areaId: areaId,
					keywords: keywords,
					PriceSorting: PriceSorting,
				};
				this.GoodsListData = []
				let orders = [] // 排序数组 
				let classifyIdType = '' // 分类id
				if (classifyId === 0) {
					classifyIdType = ""
				} else {
					classifyIdType = classifyId
				}
				let regionIdType = ''
				if (classifyId === 0) {
					regionIdType = ''
				} else {
					regionIdType = regionId
				}
				let DIRECTIONType = {
					fieldname: '',
					direction: ''
				}
				// 判断排序方式
				if (areaId === '') { // 初次加载时
					DIRECTIONType = {
						fieldname: 'iOrder',
						direction: 'asc'
					}
					orders.push(DIRECTIONType)
				} else if (areaId === 'iOrder') { // 默认方式
					DIRECTIONType = {
						fieldname: 'iOrder',
						direction: 'asc'
					}
					orders.push(DIRECTIONType)
				} else if (areaId === 'fSalePrice') {
					if (PriceSorting === 0) { // 如果为0，则默认排序
						DIRECTIONType = {
							fieldname: 'iOrder',
							direction: 'asc'
						}
						orders.push(DIRECTIONType)
					} else if (PriceSorting === 1) { // 为1则升序
						DIRECTIONType = {
							fieldname: 'fSalePrice',
							direction: 'asc'
						}
						orders.push(DIRECTIONType)
					} else if (PriceSorting === 2) { // 为2则为降序
						DIRECTIONType = {
							fieldname: 'fSalePrice',
							direction: 'desc'
						}
						orders.push(DIRECTIONType)
					}
				}
				console.log('keywords', keywords)
				let keywordsData = ''
				if (keywords === undefined) {
					console.log('111')
					keywordsData = this.ReceiveData.InputData
				} else {
					console.log('222')
					keywordsData = keywords
				}
				let goodData = {
					queryCondition: {
						order: orders, // 排序方式
						pageindex: 1,
						pagesize: 10000,
						where: [{
								fieldname: "categoryid", // 商品分类id
								valuefrom: classifyIdType,
							},
							{
								fieldname: "area_id", // 区域id
								valuefrom: regionIdType,
							},
							{
								fieldname: "keyword", // 搜索关键词
								valuefrom: keywordsData,
							},
							{
								fieldname: "shop_id", // 商品id
								valuefrom: this.$route.query.ShopID,
							}

						],
					},
				}
				this.$api.commit.GetProductList(goodData).then(res => {
					console.log('商品数据', res)
					this.getProductFavorites(res.data.data)
					if (areaId === 'fSalePrice') {
						if (PriceSorting === 0) { // 如果为0，则默认排序
							this.GoodsListData = res.data.data
							this.getProductFavorites(res.data.data)
						} else if (PriceSorting === 1) { // 为1则升序
							this.GoodsListData = (this.GoodsListData.concat(res.data.data)).sort(this.Compare(
								'fSalePrice'))
							this.getProductFavorites(res.data.data)
						} else if (PriceSorting === 2) { // 为2则为降序
							this.GoodsListData = (this.GoodsListData.concat(res.data.data)).sort(this.UnCompare(
								'fSalePrice'))
							this.getProductFavorites(res.data.data)
						}
					} else {
						this.GoodsListData = this.GoodsListData.concat(res.data.data)
						this.getProductFavorites(res.data.data)
					}
				})
			},
			// 价格升序排序
			Compare(property) {
				return function(a, b) {
					var value1 = a[property];
					var value2 = b[property];
					return value1 - value2;
				}
			},
			// 价格降序排序
			UnCompare(property) {
				return function(a, b) {
					var value1 = a[property];
					var value2 = b[property];
					return value2 - value1;
				}
			},
			// 获取个人收藏列表
			getProductFavorites(datalist) {
				let params = {
					token: localStorage.getItem('token'),
					data: {
						classId: '',
						productName: '',
						tagId: '',
						currentPage: 1,
						pagesize: 10000,
					}
				}
				this.$api.person.getProductFavorites(params).then(res => {
					if (res.code == 200) {
						this.FavorList = res.data.pager.data
						console.log('数据列表', datalist)
						this.SearchFavorites(this.FavorList, datalist)
					}

				})
			},
			// 查询该商品是否被关注
			/**
			 * FavorList 关注列表
			 * LikeList 商品信息列表
			 */
			SearchFavorites(FavorList, LikeList) {
				console.log('猜你喜欢关注列表', FavorList, LikeList)
				LikeList.forEach(element => {
					let results = FavorList.map(a => a.pid).indexOf(element.goods === undefined ? element.pid :
						element.goods.pid)
					if (results === -1) {
						this.$set(element, 'FocusStatus', false)
					} else {
						this.$set(element, 'FocusStatus', true)
					}
				})
			},

			// 关注
			focus(focus) {
				console.log('关注', focus)
				if (focus.FocusStatus) {
					let del = {
						token: localStorage.getItem('token'),
						data: {
							productId: focus.goods === undefined ? focus.pid : focus.goods.pid
						}
					}
					this.$api.good.delFavoritesByProductId(del).then(res => {
						if (res.code == 200) {
							this.GoodsTopList() // 获取商品列表
							this.$message.success(res.message);
						} else {
							this.$message.error(res.message);
						}
					});
				} else {
					let params = {
						token: localStorage.getItem('token'),
						data: {
							iShopIds: focus.shop_id === undefined ? focus.shop.id : focus.shop_id,
							ids: focus.goods === undefined ? focus.pid : focus.goods.pid
						}
					}
					this.$api.good.addToCollect(params).then(res => {
						if (res.code == 200) {
							this.GoodsTopList() // 获取商品列表
							this.$message.success(res.message);
						} else {
							this.$message.error(res.message);
						}
					})
				}
			},
			// 店铺详情
			GtShop(GtShop) {
				console.log("GtShop", GtShop.id);
				sessionStorage.setItem("ShopID", GtShop.id)
				this.$router.push({
					path: "/shopindex?id=" + GtShop.id + "&refresh=true",
				})
			},
			// 去详情
			todetail(todetail) {
				console.log('去详情', todetail)
				this.$router.push({
					path: "/fruit/detail",
					query: {
						id: todetail.pid,
						iShopId: todetail.iShopId
					},
				});
			},
		}
	}
</script>

<style lang="scss" scoped>
	#SearchPage {
		#ShopBox {
			padding: 0 16.19rem;
			margin: 2.19rem 0;

			.list_box {
				display: flex;
				flex-flow: wrap;

				.list_item:nth-child(4) {
					margin: 0 0rem 2rem 0;
				}

				.list_item {
					width: 20rem;
					background: #00dea9;
					margin: 0 2rem 2rem 0;
					display: flex;
					flex-direction: column;
					justify-content: center;
					align-items: center;

					.goods-list-itme {
						width: 20rem;
						height: 25rem;
						display: flex;
						align-items: center;
						justify-content: center;
						flex-direction: column;

						.goods-box {
							background: white;
						}

						.logo-img {
							background: white;
							width: 7rem;
							height: 7rem;
							border-radius: 100%;
							text-align: center;
							line-height: 7rem;
						}

						.goods-img {
							width: 15rem;
							height: 15rem;
							margin: 0 auto;
							text-align: center;
						}

						.name {
							font-size: 1.13rem;
							font-family: Microsoft YaHei;
							font-weight: 400;
							color: #040000;
							overflow: hidden;
							text-overflow: ellipsis;
							white-space: nowrap;
							width: 15rem;
							margin-top: 0.94rem;
							text-align: center;
						}

						.price {
							font-size: 1.5rem;
							font-family: Microsoft YaHei;
							font-weight: 400;
							color: #f3406f;
							margin-top: 0.94rem;
							width: 15rem;
							text-align: center;
						}

						.shop-name {
							font-size: 1.5rem;
							padding: 1rem 0;
							overflow: hidden;
							text-overflow: ellipsis;
							white-space: nowrap;
							width: 16.5rem;
							text-align: center;
							color: #fff;
						}

						.shop-type {
							font-size: 0.8rem;
							line-height: 1.5rem;
							border-top: white 0.1rem solid;
							border-bottom: white 0.1rem solid;
							width: 4rem;
							text-align: center;
							margin: 0 auto;
							color: #fff;
						}

						.shop-button {
							background: white;
							width: 12rem;
							height: 2rem;
							margin-top: 2rem;
							text-align: center;
							color: #18c4a6;
							line-height: 2rem;
							cursor: pointer;
						}
					}
				}
			}
		}

		#GoodsBox {
			.goods_body {
				padding: 0 16.19rem;
				margin: 2.19rem 0;
				display: flex;
				justify-content: flex-start;
				align-items: center;
				flex-wrap: wrap;

				.goods-item {
					width: 24%;
					height: 25.88rem;
					display: flex;
					flex-direction: column;
					align-items: center;
					margin-right: 1%;
					margin-bottom: 2.38rem;
					cursor: pointer;
					background: #fff;
					padding: 1rem 0;

					&:nth-child(4n) {
						margin-right: 0;
					}

					.goods-img {
						width: 100%;
						height: 20.94rem;
						display: flex;
						align-items: center;
						justify-content: center;
						background: #fff;

						img {
							width: 16rem;
							height: 16rem;
							object-fit: contain;
						}
					}

					.goods-info {
						width: 17.1rem;
						margin-top: 1.5rem;
						height: 6rem;
						display: flex;
						justify-content: space-between;
						align-content: center;
						overflow: hidden;
						text-overflow: ellipsis;
						white-space: nowrap;

						.goods-info-left {
							display: flex;
							flex-direction: column;
							width: 80%;
							-webkit-box-orient: vertical;
							-webkit-line-clamp: 2;
							overflow: hidden;

							.name {
								font-size: 1.13rem;
								font-family: Microsoft YaHei;
								font-weight: 400;
								color: rgba(0, 0, 0, 1);
								overflow: hidden;
								text-overflow: ellipsis;
								white-space: nowrap;
								width: 100%;
								display: flex;
								align-items: center;
								height: 3rem;
							}

							.price_box {
								display: flex;
								align-items: center;
								height: 3rem;

								.price {
									font-size: 1.5rem;
									font-family: Microsoft YaHei;
									font-weight: 400;
									color: rgba(243, 64, 111, 1);
								}

								.text {
									font-size: .8rem;
									font-family: Microsoft YaHei;
									font-weight: 400;
									color: #666;
									margin-left: 1rem;
									margin-top: .7rem;
								}
							}
						}

						.goods-info-right {
							display: flex;
							align-items: center;
							justify-content: center;

							.item_img {
								width: 1.5rem;
								height: 1.4rem;
							}
						}
					}
				}
			}
		}
	}
</style>
